package com.dm0858.bianmin.ui.activity;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.mine.tools.ToastUtils;
import com.dm0858.bianmin.model.response.OtherNewsListResponse;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.fragment.HomeFragment;
import com.dm0858.bianmin.ui.presenter.OtherNewsListPresenter;
import com.dm0858.bianmin.ui.presenter.ShangJiaPresenter;
import com.dm0858.bianmin.utils.CacheUtils;
import com.dm0858.bianmin.utils.DateUtils;
import com.dm0858.bianmin.view.IOtherNewsListView;
import com.dm0858.bianmin.view.IShangJiaView;
import com.dm0858.bianmin.view.IndexListViewFrame;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by yelvqing on 2018/5/1.
 */

public class OtherNewsListActivity extends BaseActivity<OtherNewsListPresenter> implements IOtherNewsListView ,IndexListViewFrame.IXListViewListener{

    public static final String STYPE = "OTHERNEWS";
    @Bind(R.id.gridview)
    GridView mgridView;

    @Bind(R.id.liv_od_content)
    IndexListViewFrame liv_od_content;

    @Bind(R.id.normal_listtitle)
    TextView normal_listtitle;


    MyAdapter myAdapter;

    int type;

    //定义图标数组
    private int[] imageRes1 = {
            R.drawable.kaisuo,
            R.drawable.shuidian,
            R.drawable.diannao,
            R.drawable.jiadian,
            R.drawable.guandao,
            R.drawable.ranju,
            R.drawable.zhuangshi,
            R.drawable.juanmen,
            R.drawable.jiazheng,
            R.drawable.banjia,
            R.drawable.paotui,
            R.drawable.songshui
    };
    //定义图标下方的名称数组
    private String[] name1 = {
            "开锁换锁",
            "水电维修",
            "电脑维修",
            "家电维修",
            "管道疏通",
            "燃具维修",
            "家装维修",
            "卷门维修",
            "家政服务",
            "搬家服务",
            "同城跑腿",
            "送桶装水",
    };
    private String[] nameid1 = {
            "0",
            "6",
            "3",
            "2",
            "5",
            "4",
            "12",
            "7",
            "8",
            "9",
            "14",
            "38"
    };
    //定义图标下方的名称数组
    private String[] name2 = {
            "租房买房",
            "二手汽车",
//            "搬家服务",
//            "家政服务",
            "宠物医疗",
//            "同城跑腿",
            "教育培训",
            "五金建材",
            "衣鞋定制",
            "批发采购",
            "超市百货"
    };
    //定义图标下方的名称数组
    private String[] nameid2 = {
            "10",
            "18",
//            "9",
//            "8",
            "11",
//            "14",
            "16",
            "1",
            "44",
            "46",
            "47",

    };
    //定义图标数组
    private int[] imageRes2 = {
            R.drawable.zmf,
            R.drawable.ershouche,
//            R.drawable.banjia,
//            R.drawable.jiazheng,
            R.drawable.chongwu,
//            R.drawable.paotui,
            R.drawable.jiaoyu,
            R.drawable.wujin,
            R.drawable.yixie,
            R.drawable.caigou,
            R.drawable.chaoshi
    };

    //定义图标下方的名称数组
    private String[] name3 = {
//            "手机订票",
            "平安代驾",
//            "送桶装水",
            "药店医疗",
            "用餐住宿",
            "婚庆摄影",
            "美容健身",
            "本地特产",
//            "衣鞋定制",
            "家电灯饰",
//            "批发采购",
//            "超市百货",
            "旅游购物街",
            "生活万花筒","玩转城市","车辆服务"

    };
    //定义图标下方的名称数组
    private String[] nameid3 = {
//            "20",
            "13",
//            "38",
            "39",
            "40",
            "41",
            "42",
            "43",
//            "44",
            "45",
//            "46",
//            "47",
            "48",
            "49",
            "50",
            "51"

    };
    //定义图标数组
    private int[] imageRes3 = {
//            R.drawable.dingpiao,
            R.drawable.carweixiu,
//            R.drawable.songshui,
            R.drawable.yaodian,
            R.drawable.yongcan,
            R.drawable.hunqin,
            R.drawable.meirong,
            R.drawable.techan,
//            R.drawable.yixie,
            R.drawable.jiadian1,
//            R.drawable.caigou,
//            R.drawable.chaoshi,
            R.drawable.lvyou,
            R.drawable.shenghuo,
            R.drawable.cheliang,
            R.drawable.chengshifuwu

    };




    private List<OtherNewsListResponse.OtherNewsListDataBean> madapter_data=new ArrayList<OtherNewsListResponse.OtherNewsListDataBean>();

    @Override
    protected OtherNewsListPresenter createPresenter()  {
        return new OtherNewsListPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_othernewslist;
    }

    @Override
    public void onGetOtherNewsListSuccess(OtherNewsListResponse newList) {
        int length=madapter_data.size();
        if (length>0)
        {
            madapter_data.clear();
        }
        madapter_data=newList.data;
        myAdapter = new MyAdapter();
        liv_od_content.setVisibility(View.VISIBLE);

        liv_od_content.setAdapter(myAdapter);
        setIndexNewsListViewHeight(liv_od_content,myAdapter,length);
        myAdapter.notifyDataSetChanged();
        onLoad();
    }

    @Override
    public void onError() {

    }

    @Override
    public void initView() {



    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        type=intent.getIntExtra(STYPE, 0);
        type++;
        mPresenter.getOtherNewsList(type+"");


        int typelength=0;
        switch (type)
        {
            case 1:
            {
                typelength=imageRes1.length;
                normal_listtitle.setText("生活服务");
                break;
            }
            case 2:
            {
                typelength=imageRes2.length;
                normal_listtitle.setText("生活信息");
                break;
            }
            case 3:
            {
                typelength=imageRes3.length;
                normal_listtitle.setText("生活便民");
                break;
            }
        }
        //生成动态数组，并且转入数据
        ArrayList<HashMap<String ,Object>> listItemArrayList=new ArrayList<HashMap<String,Object>>();
        for(int i=0; i<typelength; i++){
            HashMap<String, Object> map=new HashMap<String,Object>();
            switch (type)
            {
                case 1:
                {
                    map.put("itemImage", imageRes1[i]);
                    map.put("itemText", name1[i]);
                    break;
                }
                case 2:
                {
                    map.put("itemImage", imageRes2[i]);
                    map.put("itemText", name2[i]);
                    break;
                }
                case 3:
                {
                    map.put("itemImage", imageRes3[i]);
                    map.put("itemText", name3[i]);
                    break;
                }
            }

            listItemArrayList.add(map);
        }
        //生成适配器的ImageItem 与动态数组的元素相对应
        SimpleAdapter saImageItems = new SimpleAdapter(OtherNewsListActivity.this,
                listItemArrayList,//数据来源
                R.layout.item,//item的XML

                //动态数组与ImageItem对应的子项
                new String[]{"itemImage", "itemText"},

                //ImageItem的XML文件里面的一个ImageView,TextView ID
                new int[]{R.id.img_shoukuan, R.id.txt_shoukuan});
        //添加并且显示
        mgridView.setAdapter(saImageItems);

        //添加消息处理
        mgridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getActivity(),name[position],Toast.LENGTH_LONG).show();
                String sectionid="";
                switch (type)
                {
                    case 1:
                    {
                        sectionid=nameid1[position];
                        break;
                    }
                    case 2:
                    {
                        sectionid=nameid2[position];
                        break;
                    }
                    case 3:
                    {
                        sectionid=nameid3[position];
                        break;
                    }
                }

                KLog.e("position="+position);
                Intent intent = null;
                intent = new Intent(OtherNewsListActivity.this, NormalListActivity.class);

                intent.putExtra(NormalListActivity.SECIONID, Integer.valueOf(sectionid) );
                intent.putExtra(NormalListActivity.AREA, CacheUtils.getDriverCity(getApplicationContext()));
                intent.putExtra(NormalListActivity.LAT, CacheUtils.getDriverLat(getApplicationContext()));
                intent.putExtra(NormalListActivity.LNG, CacheUtils.getDriverLon(getApplicationContext()));

                startActivity(intent);
                return;



            }
        });
        setListViewHeightBasedOnChildren(mgridView);
        //  mgridView.deferNotifyDataSetChanged();



        liv_od_content.setPullLoadEnable(true);
        liv_od_content.setXListViewListener(this);
        registerForContextMenu(liv_od_content);
        liv_od_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(OtherNewsListActivity.this, ArticleDetailActivity.class);
                intent.putExtra(ArticleDetailActivity.id, madapter_data.get(arg2-1).id);
                startActivity(intent);

            }
        });


    }


    private void selectImg(int flag)
    {


    }

    @Override
    public void initListener() {





    }

    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 4;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }



    @Override
    public void onLoadMore() {
        onLoad();
    }


    static class ViewHolder {
        public TextView addexam_list_item_text;


    }

    public class MyAdapter extends BaseAdapter {

        ViewHolder holder = null;
        @Override
        public int getCount() {
            int count= madapter_data.size();
            return count;
        }

        @Override
        public Object getItem(int arg0) {
            int arg1=arg0;
            return madapter_data.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            int arg1=arg0;
            // TODO Auto-generated method stub
            return arg1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {

            convertView= LayoutInflater.from(OtherNewsListActivity.this).inflate(R.layout.item_text_news, null);
            ImageView fruitImage = (ImageView) convertView.findViewById(R.id.news_image);//获取该布局内的图片视图
            TextView fruitName = (TextView) convertView.findViewById(R.id.news_name);//获取该布局内的文本视图
//        fruitImage.setImageResource();//为图片视图设置图片资源

            Glide.with(OtherNewsListActivity.this).load(madapter_data.get(position).address).into(fruitImage);
            fruitName.setText(madapter_data.get(position).title);//为文本视图设置文本内容

//            TextView tiametxt = (TextView) convertView.findViewById(R.id.news_time);//获取该布局内的文本视图
//            String timestr = DateUtils.dataOne(madapter_data.get(position).addtime);
//            tiametxt.setText(DateUtils.timedate(timestr));

            return convertView;




        }


    }

    public static void setIndexNewsListViewHeight(IndexListViewFrame listView, MyAdapter adapter, int count) {
        // 获取ListView对应的Adapter

        ListAdapter listAdapter = listView.getAdapter();

        if (listAdapter == null) {

            return;

        }

        int totalHeight = 0;

        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目

            View listItem = listAdapter.getView(i, null, listView);

            listItem.measure(0, 0); // 计算子项View 的宽高

            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度

        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        // listView.getDividerHeight()获取子项间分隔符占用的高度

        // params.height最后得到整个ListView完整显示需要的高度

        listView.setLayoutParams(params);
    }

    /**
     * 正在加载时回调
     */
    private void onLoad() {
        liv_od_content.stopRefresh();
        liv_od_content.stopLoadMore();
    }

    @Override
    public void onRefresh() {
        if (madapter_data.size()>0) {
            madapter_data.clear();
        }
        mPresenter.getOtherNewsList(type+"");
    }

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }
}
